//
//  RootViewController.m
//  Aandeel
//
//  Created by Jin Hu on 2010/05/19.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "FavoriteViewController.h"
#import "SettingsViewController.h"
#import "AandeelAppDelegate.h"
#import	"FavoriteCell.h"


@implementation FavoriteViewController

#pragma mark -
#pragma mark View lifecycle

- (void)setModel:(NSMutableArray*)fav {
	if(fav==NULL){
		AandeelAppDelegate *appDelegate = (AandeelAppDelegate *)[[UIApplication sharedApplication] delegate];
		model = appDelegate.favoritesList;
		[model retain];
	}else{
	model=fav;
	[model retain];
	}
}
- (void)awakeFromNib{

}

 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	// UIBarButtonItem* saveItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRedo target:self action:@selector(saveAction:)];
	 //self.navigationItem.rightBarButtonItem = saveItem;
	 //self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBack target:self action:@selector(saveAction:)];

	 //[saveItem release];
 }

- (void)saveAction:(id)sender
{
	[(UITableView*)self.view reloadData];
}



/*
 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
 }
 */
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	printf("section: %d",[model count]);
    return 3;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	//return [[model objectAtIndex:section] count];
	int c=0;
	NSMutableArray* list =[model objectAtIndex:section];
	for (int i=0; i<[list count]; i++) {
		if ([[[list objectAtIndex:i] objectForKey:@"favorite"] isEqualToString:@"true"]) {
			c++;					                
		}
		NSString* fav = [[list objectAtIndex:i] objectForKey:@"favorite"];
		printf("fav: %s\n",[fav UTF8String]  );
	}
	printf("size: %d\n",c );
	return c;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *kCellIdentifier = @"FavoriteCell";

	FavoriteCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
	
	if (cell == nil) {
		// No reusable cell was available, so we create a new cell and configure its subviews.
		cell = [[[FavoriteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease];
	}
	NSMutableArray* list =[model objectAtIndex:indexPath.section];
	int sel=-1;
	NSDictionary* row;
	for (int i=0; i<[list count]; i++) {
		if ([[[list objectAtIndex:i] objectForKey:@"favorite"] isEqualToString:@"true"]) {
			sel++;
		}
		if (sel ==indexPath.row) {
			row = [ list objectAtIndex:i];
			break;
		}
	}
	float priceOrg  = [[[row objectForKey:@"his_price"] stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];
	float priceNow  = [[[row objectForKey:@"price"] stringByReplacingOccurrencesOfString:@"," withString:@"."] floatValue];
	float profit    = (priceNow- priceOrg) * [[row objectForKey:@"amount"] intValue];
	if([row objectForKey:@"his_price"]!=nil)
		cell.priceOrg.text= [row objectForKey:@"his_price"];
	cell.priceNow.text= [row objectForKey:@"price"];
	cell.change.text=   [NSString stringWithFormat:@"%.02f", (priceNow-priceOrg)];
	cell.percentage.text= [NSString stringWithFormat:@"%.02f %", (priceNow-priceOrg)/priceOrg];
	cell.profit.text= [NSString stringWithFormat:@"%.02f", profit];
	if([row objectForKey:@"amount"]!=nil)
		cell.unit.text	=[row objectForKey:@"amount"];
	
	cell.logo.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@.png",[row objectForKey:@"name"]]];
	if(cell.logo.image==nil){
		cell.name.text = [row objectForKey:@"name"];
	}
	if (profit>0) {
		cell.indicator.image = [UIImage imageNamed:@"up.gif"];
	}else{
		cell.indicator.image = [UIImage imageNamed:@"down.gif"];
	}	
	return cell;
}

// Override to support conditional editing of the table view.
// - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
// return YES;
// }


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSMutableDictionary* selected;
	NSMutableArray* list =[model objectAtIndex:indexPath.section];
	int sel=-1;
	NSDictionary* row;
	for (int i=0; i<[list count]; i++) {
		if ([[[list objectAtIndex:i] objectForKey:@"favorite"] isEqualToString:@"true"]) {
			sel++;
		}
		if (sel ==indexPath.row) {
			selected = [ list objectAtIndex:i];
			break;
		}
	}
	
		// Navigation logic may go here. Create and push another view controller.
		SettingsViewController *settingsViewController = [[SettingsViewController alloc] initWithNibName:@"SettingsView" bundle:nil];
		[settingsViewController setModel:selected];
		[self.navigationController pushViewController:settingsViewController animated:YES];
	[settingsViewController setParrentController:self];
		[settingsViewController release];
		
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
	[super didReceiveMemoryWarning];
	
	// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
	// For example: self.myOutlet = nil;
}


- (void)dealloc {
	[super dealloc];
}
-(void)saveChange{
	[self.view reloadData];
	[[NSUserDefaults standardUserDefaults] setObject:model forKey:APP_KEY];

}
@end

